<!-- 更新用户资料 -->
<template>
    <div class="box">
        <div class="top">
            <div class="back" @click="$router.back()">
                <svgIcon iconName="icon-fanhui" font-size="40px"></svgIcon>
            </div>
            <div class="top_title">编辑资料</div>
        </div>
        <div class="content">
            <img class="cont_pic" :src="avatarUrl" alt="" @click="handleAvatarClick">
            <input 
                type="file" 
                ref="fileInput" 
                accept="image/*" 
                style="display: none" 
                @change="handleFileChange"
            >
            <div class="cont_item">
                <div class="item" @click="handleInputClick('nickname')">
                    <div class="item_left">
                        名称
                    </div>
                    <div class="item_center">
                        <input 
                            v-model="userInfo.nickname"
                            class="inline-input"
                            @blur="handleInputBlur('nickname')"
                            @keyup.enter="handleInputBlur('nickname')"
                            ref="nicknameInput"
                        >
                    </div>
                    <div>
                        <svgIcon iconName="icon-youjiantou" font-size="30px"></svgIcon>
                    </div>
                </div>
                <div class="item">
                    <div class="item_left">
                        小红书号
                    </div>
                    <div class="item_center">{{ userInfo.redbookId }}</div>
                    <div>
                        <svgIcon iconName="icon-youjiantou" font-size="30px"></svgIcon>
                    </div>
                </div>
            </div>
            <div class="cont_item">
                <div class="item" style="border: none;" @click="handleInputClick('signature')">
                    <div class="item_left">
                        简介
                    </div>
                    <div class="item_center">
                        <input 
                            v-model="values.signature"
                            class="inline-input"
                            @blur="handleInputBlur('signature')"
                            @keyup.enter="handleInputBlur('signature')"
                            ref="signatureInput"
                        >
                    </div>
                    <div>
                        <svgIcon iconName="icon-youjiantou" font-size="30px"></svgIcon>
                    </div>
                </div>
            </div>
            <div class="cont_item">
                <div class="item" @click="showGenderPicker = true">
                    <div class="item_left">
                        性别
                    </div>
                    <div class="item_center">{{ formatGender(values.gender) }}</div>
                    <div>
                        <svgIcon iconName="icon-youjiantou" font-size="30px"></svgIcon>
                    </div>
                </div>
                <div class="item" @click="showDatePicker = true">
                    <div class="item_left">
                        生日
                    </div>
                    <div class="item_center">{{ formatDate(values.birthday) }}</div>
                    <div>
                        <svgIcon iconName="icon-youjiantou" font-size="30px"></svgIcon>
                    </div>
                </div>
                <div class="item" @click="showAreaPicker = true">
                    <div class="item_left">
                        地区
                    </div>
                    <div class="item_center">{{ formatArea(values.area) }}</div>
                    <div>
                        <svgIcon iconName="icon-youjiantou" font-size="30px"></svgIcon>
                    </div>
                </div>
                <div class="item" @click="showJobPicker = true">
                    <div class="item_left">
                        职业
                    </div>
                    <div class="item_center">{{ formatJob(values.job) }}</div>
                    <div>
                        <svgIcon iconName="icon-youjiantou" font-size="30px"></svgIcon>
                    </div>
                </div>
                <div class="item" style="border: none;" @click="handleInputClick('school')">
                    <div class="item_left">
                        学校
                    </div>
                    <div class="item_center">
                        <input 
                            v-model="values.school"
                            class="inline-input"
                            @blur="handleInputBlur('school')"
                            @keyup.enter="handleInputBlur('school')"
                            ref="schoolInput"
                        >
                    </div>
                    <div>
                        <svgIcon iconName="icon-youjiantou" font-size="30px"></svgIcon>
                    </div>
                </div>
            </div>
        </div>
        <div class="bottom">
            <button 
                :class="{ 'button-changed': hasChanges }" 
                @click="handleSave"
                :disabled="!hasChanges"
            >保存</button>
        </div>
    </div>

    <!-- 性别选择器 -->
    <van-popup v-model:show="showGenderPicker" position="bottom" round>
        <van-picker
            v-model="values.gender"
            :columns="genderColumns"
            @confirm="onGenderConfirm"
            @cancel="showGenderPicker = false"
            title="选择性别"
            show-toolbar
            class="custom-picker"
        />
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom" round>
        <van-date-picker
            v-model="values.birthday"
            title="选择生日"
            :min-date="minDate"
            :max-date="maxDate"
            type="date"
            @confirm="onDateConfirm"
            @cancel="showDatePicker = false"
            class="custom-picker"
        />
    </van-popup>

    <!-- 地区选择器 -->
    <van-popup v-model:show="showAreaPicker" position="bottom" round>
        <van-picker
            v-model="values.area"
            :columns="areaColumns"
            @confirm="onAreaConfirm"
            @cancel="showAreaPicker = false"
            title="选择地区"
            show-toolbar
            class="custom-picker"
        />
    </van-popup>

    <!-- 职业选择器 -->
    <van-popup v-model:show="showJobPicker" position="bottom" round>
        <van-picker
            v-model="values.job"
            :columns="jobColumns"
            @confirm="onJobConfirm"
            @cancel="showJobPicker = false"
            title="选择职业"
            show-toolbar
            class="custom-picker"
        />
    </van-popup>

    <input 
        type="file" 
        ref="bgFileInput" 
        accept="image/*" 
        style="display: none" 
        @change="handleBgFileChange"
    >
</template>
<script setup>
    import { ref, onMounted, nextTick, watch } from 'vue'
    import { Popup, Picker, DatePicker, showToast } from 'vant'
    import axios from 'axios'
    import defaultAvatar from '../../assets/czq/pic.png'
    import { useRouter } from 'vue-router'
    
    const router = useRouter()

    // 头像相关
    const fileInput = ref(null)
    const avatarUrl = ref(defaultAvatar)

    // 用户信息
    const userInfo = ref({
        nickname: '',
        redbookId: '',
        avatar: ''
    })

    // 其他值
    const values = ref({
        signature: '暂时未设置',
        school: '暂时未设置',
        gender: ['选择性别'],
        birthday: ['2005','01','01'],
        area: ['选择地区'],
        job: ['选择职业']
    })

    // 编辑相关
    const editingField = ref('')
    const nicknameInput = ref(null)
    const signatureInput = ref(null)
    const schoolInput = ref(null)

    // 背景图相关
    const bgFileInput = ref(null)

    // 监听值是否发生变化
    const hasChanges = ref(false)
    const initialValues = ref(null)

    // 获取用户信息
    const getUserInfo = async () => {
        try {
            const userId = localStorage.getItem('user_id')
            if (!userId) {
                showToast('未登录')
                return
            }

            const response = await axios.get(`http://1.14.98.17:8765/api/users/${userId}`)
            if (response.data.success === true) {
                const data = response.data.data
                userInfo.value = {
                    nickname: data.nickname || '未设置昵称',
                    redbookId: data.user_id || '未设置小红书号',
                    avatar: data.avatar_url || defaultAvatar
                }
                // 更新头像URL
                avatarUrl.value = userInfo.value.avatar

                // 获取用户详情
                const profileResponse = await axios.get(`http://1.14.98.17:8765/api/profile/${userId}`)
                if (profileResponse.data.success === true) {
                    const bio = profileResponse.data.data.bio || ''
                    const bioArray = bio.split('。')
                    
                    // 更新values中的值
                    values.value = {
                        signature: bioArray[0] || '暂时未设置',
                        school: bioArray[5] || '暂时未设置',
                        gender: [bioArray[1] || '选择性别'],
                        birthday: bioArray[2] ? bioArray[2].split('-') : ['2005', '01', '01'],
                        area: bioArray[3] ? bioArray[3].split(' ') : ['选择地区'],
                        job: [bioArray[4] || '选择职业']
                    }
                }

                // 在获取用户信息后保存初始值
                initialValues.value = {
                    nickname: userInfo.value.nickname,
                    avatar: avatarUrl.value,
                    signature: values.value.signature,
                    school: values.value.school,
                    gender: [...values.value.gender],
                    birthday: [...values.value.birthday],
                    area: [...values.value.area],
                    job: [...values.value.job]
                }
            } else {
                showToast(response.data.message || '获取用户信息失败')
            }
        } catch (error) {
            console.error('获取用户信息失败:', error)
            showToast('获取用户信息失败')
        }
    }

    // 在组件挂载时获取用户信息
    onMounted(() => {
        getUserInfo()
    })

    const handleAvatarClick = () => {
        fileInput.value.click()
    }

    const handleFileChange = (event) => {
        const file = event.target.files[0];
        if (!file) return

        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            showToast('请选择图片文件')
            return
        }

        // 检查文件大小（限制为5MB）
        if (file.size > 5 * 1024 * 1024) {
            showToast('图片大小不能超过5MB')
            return
        }

        // 创建文件预览URL
        const reader = new FileReader()
        reader.onload = (e) => {
            avatarUrl.value = e.target.result
        }
        reader.readAsDataURL(file)
    }

    // 性别选择
    const showGenderPicker = ref(false)
    const genderColumns = [
        {
            text: '男',
            value: '男'
        },
        {
            text: '女',
            value: '女'
        }
    ]

    const onGenderConfirm = (value) => {
        if (Array.isArray(value)) {
            values.value.gender = value
        } else if (value && value.selectedValues) {
            values.value.gender = value.selectedValues
        }
        showGenderPicker.value = false
    }

    // 日期选择
    const showDatePicker = ref(false)
    const minDate = new Date(2000, 0, 1)
    const maxDate = new Date()

    const onDateConfirm = (value) => {
        if (Array.isArray(value)) {
            values.value.birthday = value
        } else if (value && value.selectedValues) {
            values.value.birthday = value.selectedValues
        }
        showDatePicker.value = false
    }

    // 格式化日期显示
    const formatDate = (date) => {
        if (!date) return ''
        if (Array.isArray(date)) {
            return date.join('-')
        }
        const d = new Date(date)
        const year = d.getFullYear()
        const month = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        return `${year}-${month}-${day}`
    }

    // 地区选择
    const showAreaPicker = ref(false)
    const areaColumns = [
        {
            text: '四川',
            value: '四川',
            children: [
                { text: '泸州', value: '泸州' },
                { text: '成都', value: '成都' },
                { text: '绵阳', value: '绵阳' },
                { text: '德阳', value: '德阳' },
                { text: '宜宾', value: '宜宾' }
            ]
        },
        {
            text: '北京',
            value: '北京',
            children: [
                { text: '北京', value: '北京' }
            ]
        },
        {
            text: '上海',
            value: '上海',
            children: [
                { text: '上海', value: '上海' }
            ]
        }
    ]

    const onAreaConfirm = (value) => {
        if (Array.isArray(value)) {
            values.value.area = value
        } else if (value && value.selectedValues) {
            values.value.area = value.selectedValues
        }
        showAreaPicker.value = false
    }

    // 职业选择
    const showJobPicker = ref(false)
    const jobColumns = [
        {
            text: '学生',
            value: '学生'
        },
        {
            text: '教师',
            value: '教师'
        },
        {
            text: '工程师',
            value: '工程师'
        },
        {
            text: '医生',
            value: '医生'
        },
        {
            text: '设计师',
            value: '设计师'
        },
        {
            text: '自由职业',
            value: '自由职业'
        },
        {
            text: '其他',
            value: '其他'
        }
    ]

    const onJobConfirm = (value) => {
        if (Array.isArray(value)) {
            values.value.job = value
        } else if (value && value.selectedValues) {
            values.value.job = value.selectedValues
        }
        showJobPicker.value = false
    }

    // 格式化显示函数
    const formatGender = (value) => value[0]
    const formatArea = (value) => value.join(' ')
    const formatJob = (value) => value[0]

    // 处理输入框点击
    const handleInputClick = (type) => {
        // 清空原来的内容
        if (type === 'nickname') {
            userInfo.value.nickname = ''
        } else {
            values.value[type] = ''
        }
        nextTick(() => {
            switch (type) {
                case 'nickname':
                    nicknameInput.value?.focus()
                    break
                case 'signature':
                    signatureInput.value?.focus()
                    break
                case 'school':
                    schoolInput.value?.focus()
                    break
            }
        })
    }

    // 处理输入框失焦
    const handleInputBlur = (type) => {
        // 可以在这里添加其他处理逻辑
    }

    // 监听数据变化并打印拼接的字符串
    const printCombinedValues = () => {
        const valueArray = [
            values.value.signature || '未设置简介',
            formatGender(values.value.gender) || '未设置性别',
            formatDate(values.value.birthday) || '未设置生日',
            formatArea(values.value.area) || '未设置地区',
            formatJob(values.value.job) || '未设置职业',
            values.value.school || '未设置学校'
        ]
        const combinedString = valueArray.join('。')
        console.log('拼接的字符串:', combinedString)
    }

    // 监听所有相关数据的变化
    watch(
        [
            () => userInfo.value.nickname,
            () => avatarUrl.value,
            () => values.value.signature,
            () => values.value.school,
            () => values.value.gender,
            () => values.value.birthday,
            () => values.value.area,
            () => values.value.job
        ],
        () => {
            printCombinedValues()
            // 检查是否有变化
            if (initialValues.value) {
                const hasNicknameChanged = userInfo.value.nickname !== initialValues.value.nickname
                const hasAvatarChanged = avatarUrl.value !== initialValues.value.avatar
                const hasSignatureChanged = values.value.signature !== initialValues.value.signature
                const hasSchoolChanged = values.value.school !== initialValues.value.school
                const hasGenderChanged = JSON.stringify(values.value.gender) !== JSON.stringify(initialValues.value.gender)
                const hasBirthdayChanged = JSON.stringify(values.value.birthday) !== JSON.stringify(initialValues.value.birthday)
                const hasAreaChanged = JSON.stringify(values.value.area) !== JSON.stringify(initialValues.value.area)
                const hasJobChanged = JSON.stringify(values.value.job) !== JSON.stringify(initialValues.value.job)

                hasChanges.value = hasNicknameChanged || hasAvatarChanged || hasSignatureChanged || 
                                 hasSchoolChanged || hasGenderChanged || hasBirthdayChanged || 
                                 hasAreaChanged || hasJobChanged

                console.log('值变化检测:', {
                    hasNicknameChanged,
                    hasAvatarChanged,
                    hasSignatureChanged,
                    hasSchoolChanged,
                    hasGenderChanged,
                    hasBirthdayChanged,
                    hasAreaChanged,
                    hasJobChanged,
                    hasChanges: hasChanges.value
                })
            }
        },
        { immediate: true, deep: true }
    )

    // 处理保存按钮点击
    const handleSave = async () => {
        if (!hasChanges.value) return

        try {
            const userId = localStorage.getItem('user_id')
            
            // 检查哪些值发生了变化
            const hasNicknameChanged = userInfo.value.nickname !== initialValues.value.nickname
            const hasAvatarChanged = avatarUrl.value !== initialValues.value.avatar
            const hasOtherValuesChanged = 
                values.value.signature !== initialValues.value.signature ||
                values.value.school !== initialValues.value.school ||
                JSON.stringify(values.value.gender) !== JSON.stringify(initialValues.value.gender) ||
                JSON.stringify(values.value.birthday) !== JSON.stringify(initialValues.value.birthday) ||
                JSON.stringify(values.value.area) !== JSON.stringify(initialValues.value.area) ||
                JSON.stringify(values.value.job) !== JSON.stringify(initialValues.value.job)

            let avatarPath = null

            // 如果头像发生变化，先上传头像
            if (hasAvatarChanged) {
                try {
                    // 将 base64 转换为 Blob
                    const base64Data = avatarUrl.value.split(',')[1]
                    const byteCharacters = atob(base64Data)
                    const byteArrays = []
                    for (let offset = 0; offset < byteCharacters.length; offset += 512) {
                        const slice = byteCharacters.slice(offset, offset + 512)
                        const byteNumbers = new Array(slice.length)
                        for (let i = 0; i < slice.length; i++) {
                            byteNumbers[i] = slice.charCodeAt(i)
                        }
                        const byteArray = new Uint8Array(byteNumbers)
                        byteArrays.push(byteArray)
                    }
                    const blob = new Blob(byteArrays, { type: 'image/jpeg' })
                    const file = new File([blob], 'avatar.jpg', { type: 'image/jpeg' })

                    // 创建 FormData 对象
                    const formData = new FormData()
                    formData.append('avatar', file)

                    // 上传头像
                    const uploadResponse = await axios.post('http://1.14.98.17:8765/api/upload/avatar', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    })

                    if (uploadResponse.data.success) {
                        avatarPath = uploadResponse.data.data.path
                        showToast({
                            message: '头像上传成功',
                            position: 'center',
                            duration: 2000
                        })
                    } else {
                        throw new Error(uploadResponse.data.message || '头像上传失败')
                    }
                } catch (error) {
                    console.error('头像上传失败:', error)
                    showToast({
                        message: '头像上传失败',
                        position: 'center',
                        duration: 2000
                    })
                    return
                }
            }

            // 如果基本信息发生变化，更新基本信息
            if (hasNicknameChanged || hasAvatarChanged) {
                const updateData = {
                    nickname: userInfo.value.nickname,
                    avatar_url: avatarPath || userInfo.value.avatar
                }
                const response = await axios.put(`http://1.14.98.17:8765/api/users/${userId}`, updateData)
                if (response.data.success === true) {
                    showToast({
                        message: '基本信息更新成功',
                        position: 'center',
                        duration: 2000
                    })
                }
            }

            // 如果其他值发生变化，更新简介
            if (hasOtherValuesChanged) {
                const bioArray = [
                    values.value.signature || '未设置简介',
                    formatGender(values.value.gender) || '未设置性别',
                    formatDate(values.value.birthday) || '未设置生日',
                    formatArea(values.value.area) || '未设置地区',
                    formatJob(values.value.job) || '未设置职业',
                    values.value.school || '未设置学校'
                ]
                const bio = bioArray.join('。')

                const bioResponse = await axios.put(`http://1.14.98.17:8765/api/profile/${userId}/bio`, {
                    bio: bio
                })

                if (bioResponse.data.success === true) {
                    showToast({
                        message: '简介更新成功',
                        position: 'center',
                        duration: 2000
                    })
                }
            }

            // 更新初始值
            initialValues.value = {
                nickname: userInfo.value.nickname,
                avatar: avatarUrl.value,
                signature: values.value.signature,
                school: values.value.school,
                gender: [...values.value.gender],
                birthday: [...values.value.birthday],
                area: [...values.value.area],
                job: [...values.value.job]
            }
            hasChanges.value = false

            // 保存成功后直接跳转到个人主页
            router.push('/me')

        } catch (error) {
            console.error('保存失败:', error)
            showToast({
                message: '保存失败',
                position: 'center',
                duration: 2000
            })
        }
    }
    
</script>
<style lang="less" scoped>
.box {
    width: 100%;
    // min-height: 100vh;
    background-color: #f5f5f5;
    .top {
      width: 100%;
      height: 100px;
      font-size: 32px;
      display: flex;
      align-items: center;
      .back {
        width: 100px;
        height: 100%;
        line-height: 100px;
        text-align: center;
      }
      .top_title {
        margin-left: 230px;
      }
    }
    .content {
        width: 100%;
        padding: 0 30px;
        .cont_pic {
            display: block;
           width: 150px;
           height: 150px;
           border-radius: 50%;
           margin: 50px auto;
           cursor: pointer;
           object-fit: cover;
           &:hover {
               opacity: 0.8;
           }
        }
        .cont_item {
            width: 100%;
            margin-top: 30px;
            border-radius: 30px;
            background-color: #fff;
            .item_bord {
                border: none !important;
            }
            .item {
                width: 100%;
                min-height: 90px;
                display: flex;
                align-items: center;
                border-bottom: 1px solid gray;
                font-size: 32px;
                padding: 0 30px;
                .item_left {
                    width: 190px;
                    color: gray;
                }
                .item_center {
                    width: 410px;
                    img {
                        display: block;
                        width: 100px;
                        height: 70px;
                        border-radius: 20px;
                    }
                }
            }
            .item_2 {
                width: 100%;
                height: 100px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 32px;
                padding: 0 30px;
            }
        }
    }
    .bottom {
        position: fixed;
        left: 0;
        bottom: 0;
        width: 100%;
        z-index: 10px;
        padding: 30px;
        button {
            width: 100%;
            height: 80px;
            background-color: #d26363;
            color: #fff;
            text-align: center;
            line-height: 80px;
            border-radius: 40px;
            font-size: 32px;
            transition: all 0.3s ease;

            &.button-changed {
                background-color: red;
            }

            &:disabled {
                background-color: #d26363;
                opacity: 0.5;
                cursor: not-allowed;
            }
        }
    }
}

:deep(.custom-picker) {
    .van-picker__toolbar {
        height: 100px;
        line-height: 100px;
        font-size: 32px;
    }
    
    .van-picker__title {
        height: 50px;
        line-height: 50px;
        font-size: 32px;
    }
    
    .van-picker__cancel,
    .van-picker__confirm {
        font-size: 32px;
        padding: 0 30px;
    }
    
    .van-picker-column {
        font-size: 32px;
    }
    
    .van-picker__frame {
        height: 100px;
    }
    
    .van-picker-column__item {
        height: 100px;
        line-height: 100px;
    }
}

:deep(.van-popup) {
    border-radius: 30px 30px 0 0;
}

.inline-input {
    width: 100%;
    height: 100%;
    border: none;
    outline: none;
    font-size: 32px;
    background: transparent;
    padding: 0;
    margin: 0;
    color: inherit;
}

.item_center {
    width: 410px;
    display: flex;
    align-items: center;
    
    img {
        display: block;
        width: 100px;
        height: 70px;
        border-radius: 20px;
        cursor: pointer;
        &:hover {
            opacity: 0.8;
        }
    }
}

</style>